/*
 * @author: liubing
 * @Date: 2020-07-19 15:36:09
 * @desc: Quest3 创建一个简单图形，用图片取色，随着时间变化，显示的图片要有变化
 */

const vs_source = `
    attribute vec4 a_Position;
    attribute vec2 a_TexCoord;
    varying vec2 v_TexCoord;
    void main(){
        gl_Position = a_Position;
        v_TexCoord = a_TexCoord;
    }
    `;

const fs_source = `
    precision mediump float;
    varying vec2 v_TexCoord;
    uniform sampler2D u_Sampler;
    void main(){
        gl_FragColor = texture2D(u_Sampler,v_TexCoord);
    }`;

const ANGLE_STEP = 45.0;
const COLOR_CHANGE_STEP = 250;
// let  g_last = Date.now();
let g_last;
let texArray = [
    0.0, 1.0,
    0.0, 0.0, 
    1.0, 1.0, 
    1.0, 0.0 ];

// 
function animate(angle) {
    let now = Date.now();
    g_last = g_last || now;

    let elapsed = now - g_last;
    g_last = now;

    var newAngle = angle + (ANGLE_STEP * elapsed) / 1000.0;
    return newAngle %= 360;
}

let last_frame;

function randomTexCoord() {
    let now = Date.now();
    last_frame = last_frame || now;
    let elapsed = now - last_frame;
    // elapsed = 0
    if (elapsed > COLOR_CHANGE_STEP) {
        last_frame = now;
        texArray = [
            Math.random(), Math.random(), 
            Math.random(), Math.random(), 
            Math.random(), Math.random(),
            Math.random(), Math.random(),
        ];
    } else {
        texArray = texArray;
    }
    return texArray;
}


function draw(gl, n, texCooord) {

    if (isTextureLoaded ){
        let a_TexCoord = gl.getAttribLocation(gl.program, 'a_TexCoord');
        if(!a_TexCoord){
            console.log("a_TexCoord Failed!!");
            return;
        }
    
        let texCoord = new Float32Array(texCooord);
        gl.bufferData(gl.ARRAY_BUFFER,texCoord,gl.STATIC_DRAW);
    
        gl.clear(gl.COLOR_BUFFER_BIT);    
        gl.drawArrays(gl.TRIANGLE_STRIP, 0, n);
    }
}

function initVertexBuffers(gl) {

    var verticesTexCoords = new Float32Array([
        // Vertex coordinates, texture coordinate
        -0.5,  0.5,   
        -0.5, -0.5,  
         0.5,  0.5, 
         0.5, -0.5,
      ]);
    var n = 4; // The number of vertices

    var vertexBuffer = gl.createBuffer();
    if (!vertexBuffer) {
        console.log('Failed to create Buffer Object');
        return -1;
    }
    gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, verticesTexCoords, gl.STATIC_DRAW);


    var FSIZE = verticesTexCoords.BYTES_PER_ELEMENT;
    let a_Position = gl.getAttribLocation(gl.program, 'a_Position');
    if (a_Position < 0) {
        console.log("Failed to get Position");
        return -1;
    }
    gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);
    gl.enableVertexAttribArray(a_Position)


    let texCoordBuffer = gl.createBuffer();
    if(!texCoordBuffer){
        console.log("Failed to create the texCoordBuffer");
        return -1
    }
    
    gl.bindBuffer(gl.ARRAY_BUFFER,texCoordBuffer);
    var a_TexCoord = gl.getAttribLocation(gl.program, 'a_TexCoord');
    if (a_TexCoord < 0) {
        console.log('Failed to get the storage location of a_TexCoord');
        return -1;
    }
    gl.vertexAttribPointer(a_TexCoord, 2, gl.FLOAT,false, 0,0);
    gl.enableVertexAttribArray(a_TexCoord);  // Enable the assignment of the buffer object


    return n;
}

function initTextures(gl, n) {

    var texture = gl.createTexture(); // Create a texture object
    if (!texture) {
        console.log('Failed to create the texture object');
        return false;
    }

    // Get the storage location of u_Sampler
    var u_Sampler = gl.getUniformLocation(gl.program, 'u_Sampler');
    if (!u_Sampler) {
        console.log('Failed to get the storage location of u_Sampler');
        return false;
    }
    var image = new Image(); // Create the image object
    if (!image) {
        console.log('Failed to create the image object');
        return false;
    }
    image.src = './resources/sky_cloud.jpg';
    // Register the event handler to be called on loading an image
    image.onload = function () {
        loadTexture(gl, n, texture, u_Sampler, image);
    };
    // Tell the browser to load an image
    

    return true;
}

var isTextureLoaded = false
function loadTexture(gl, n, texture, u_Sampler, image) {
    gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1); // Flip the image's y axis
    // Enable texture unit0
    gl.activeTexture(gl.TEXTURE0);
    // Bind the texture object to the target
    gl.bindTexture(gl.TEXTURE_2D, texture);

    // Set the texture parameters
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
    // Set the texture image
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, image);
    // Set the texture unit 0 to the sampler
    gl.uniform1i(u_Sampler, 0);

    isTextureLoaded = true 
}


function main() {

    let canvas = document.getElementById("glCanvas");
    const gl = canvas.getContext('webgl');
    if (!gl) {
        console.log("WebGL Failed");
        return;
    }
    console.log("width", canvas.width)
    console.log("height", canvas.height)
    gl.viewport(0, 0, canvas.width, canvas.height)

    if (!initShaders(gl, vs_source, fs_source)) {
        console.error("Failed init Shader");
        return;
    }

    let n = initVertexBuffers(gl)
    if (n < 0) {
        console.error("initVertexBuffer Failed");
        return;
    }

    // Set texture
    if (!initTextures(gl, n)) {
        console.log('Failed to intialize the texture.');
        return;
    }

    gl.clearColor(0, 0, 0.5, 1);
    var tick = function () {
        let texCooord = randomTexCoord()
        draw(gl, n,texCooord);
        requestAnimationFrame(tick);
    }
    tick();
}